//
//  MyViewController.m
//  Hai
//
//  Created by 千金贷 on 16/2/23.
//  Copyright © 2016年 wangzijian. All rights reserved.
//

#import "RegisterController.h"

@interface RegisterController ()

@end

@implementation RegisterController{
    
    AFHTTPRequestOperationManager *_manager;
}

- (void)viewDidLoad {
    [super viewDidLoad]; 
    _manager = [AFHTTPRequestOperationManager manager];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"注册"; 
    UIBezierPath * maskPath = [UIBezierPath bezierPathWithRoundedRect:_timeButton.bounds
                                                    byRoundingCorners:(UIRectCornerTopRight|UIRectCornerBottomRight)
                                                          cornerRadii:CGSizeMake(5.f, 5.f)];
    _cptext.keyboardType = UIKeyboardTypeNumberPad;
    // Create the shape layer and set its path
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.frame = _timeButton.bounds;
    maskLayer.path = maskPath.CGPath;
    // Set the newly created shape layer as the mask for the image view's layer
    _timeButton.layer.mask = maskLayer;
    [_timeButton.layer setMasksToBounds:YES];
    _tel.layer.borderColor = ButtonGray.CGColor;
    _cp.layer.borderColor = ButtonGray.CGColor;
    _pwd1.layer.borderColor = ButtonGray.CGColor;
    _pwd2.layer.borderColor = ButtonGray.CGColor;
    _danxuan.selected = YES;
    [_danxuan setImage:[UIImage imageNamed:@"reg_no"] forState:UIControlStateNormal];
    [_danxuan setImage:[UIImage imageNamed:@"reg_yes"] forState:UIControlStateSelected];
    [_danxuan addTarget:self action:@selector(checkboxClick:) forControlEvents:UIControlEventTouchUpInside];
}
-(void)checkboxClick:(UIButton *)btn
{
    if (btn.selected) {
        _nextButton.backgroundColor = ButtonGray;
        _nextButton.backgroundColor = ButtonGray;
        [_nextButton setEnabled:NO];
    }else{
        [_nextButton setEnabled:YES];
        _nextButton.backgroundColor = PinkColor;
        _nextButton.backgroundColor = PinkColor;
        
    }
    btn.selected = !btn.selected;
}
-(void)startTime{
    if (_teltext.text.length==0) {
        [[[UIAlertView alloc] initWithTitle: @"请输入手机号" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
        return;
    }
    __block int timeout=59; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                _timeButton.backgroundColor = PinkColor;
                [_timeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
                _timeButton.userInteractionEnabled = YES;
                
            });
        }else{
            int seconds = timeout % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                ////NSLog(@"____%@",strTime);
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDuration:1];
                _timeButton.backgroundColor = ButtonGray;
                [_timeButton setTitle:[NSString stringWithFormat:@"%@秒后重新发送",strTime] forState:UIControlStateNormal];
                [UIView commitAnimations];
                _timeButton.userInteractionEnabled = NO;
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
    NSString *url=[NSString stringWithFormat:@"%@sms/sendCode",BaseURL];
    NSDictionary *parameters = @{@"telnum":_teltext.text,@"codeType":@1};
    AFHTTPRequestOperation*op= [_manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSError*error;
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
        //NSLog(@"%@",dic);
        NSString *result = dic[@"code"];
            if ([result isEqualToString:@"4000"]) {
                  [[[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"验证码已发送至%@****%@",[_teltext.text substringToIndex:3],[_teltext.text substringFromIndex:7]] message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
                _teltext.userInteractionEnabled = NO;
            }else if ([result isEqualToString:@"1207"]){
                [[[UIAlertView alloc] initWithTitle: @"发送失败，请稍后再试" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
                dispatch_source_cancel(_timer);
                dispatch_async(dispatch_get_main_queue(), ^{
                    //设置界面的按钮显示 根据自己需求设置
                    _timeButton.backgroundColor = PinkColor;
                    [_timeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
                    _timeButton.userInteractionEnabled = YES;
                    
                });
                return;
                
            }else if ([result isEqualToString:@"1019"]){
                [[[UIAlertView alloc] initWithTitle: @"手机号已注册" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
                dispatch_source_cancel(_timer);
                dispatch_async(dispatch_get_main_queue(), ^{
                    //设置界面的按钮显示 根据自己需求设置
                   _timeButton.backgroundColor = [UIColor colorWithRed:40.0f/255.0f green:180.0f/255.0f blue:180.0f/255.0f alpha:1.0f];
                    [_timeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
                    _timeButton.userInteractionEnabled = YES;
                    
                });
                return;
                
            }else if ([result isEqualToString:@"1017"]){
                [[[UIAlertView alloc] initWithTitle: @"手机号不能为空" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
                dispatch_source_cancel(_timer);
                dispatch_async(dispatch_get_main_queue(), ^{
                    //设置界面的按钮显示 根据自己需求设置
                   _timeButton.backgroundColor = PinkColor;
                    [_timeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
                    _timeButton.userInteractionEnabled = YES;
                    
                });
                return;
                
            }else if([result isEqualToString:@"1018"]){
                [[[UIAlertView alloc] initWithTitle: @"手机号格式错误" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
                dispatch_source_cancel(_timer);
                dispatch_async(dispatch_get_main_queue(), ^{
                    //设置界面的按钮显示 根据自己需求设置
                   _timeButton.backgroundColor = PinkColor;
                    [_timeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
                    _timeButton.userInteractionEnabled = YES;
                    
                });
                return;
                
            } 
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [[[UIAlertView alloc] initWithTitle: @"网络异常" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
       NSLog(@"网络异常，error = %@",error.localizedDescription);
        _timeButton.backgroundColor = PinkColor;
         _timeButton.userInteractionEnabled = YES;
        [_timeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        return;
    }];
    op.responseSerializer = [AFCompoundResponseSerializer serializer];
    [op start];
    
}


- (IBAction)next{
    if (_pwd1text.text.length==0) {
        [[[UIAlertView alloc] initWithTitle: @"请输入密码" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
        return;
    }
    if (_cptext.text.length==0) {
        [[[UIAlertView alloc] initWithTitle: @"请输入验证码" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
        return;
    }
    if (_teltext.text.length==0) {
        [[[UIAlertView alloc] initWithTitle: @"请输入手机号" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
        return;
    }
    if (_pwd1text.text.length<8) {
        [[[UIAlertView alloc] initWithTitle: @"密码长度不能小于8位" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
        return;
    }
    if (![Util isValidatePwd:_pwd1text.text]) {
        [[[UIAlertView alloc] initWithTitle: @"密码必须由数字和字母组成" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
        return;
    }
    if (_pwd2text.text.length==0) {
        [[[UIAlertView alloc] initWithTitle: @"请输入确认密码" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
        return;
    }
    if (![_pwd1text.text isEqualToString:_pwd2text.text]) {
        [[[UIAlertView alloc] initWithTitle: @"两次密码输入不一致" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
        return;
    }
    
    if (!_danxuan.selected) {
        [[[UIAlertView alloc] initWithTitle: @"请同意并阅读各项协议！" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
        return;
    }
    _nextButton.backgroundColor = ButtonGray;
    [_nextButton setEnabled:NO];
    NSString * pwdtext = [Util getMd5_32Bit_String:_pwd2text.text];
    NSString *url=[NSString stringWithFormat:@"%@login/register",BaseURL];
    NSDictionary *parameters;
        parameters = @{@"mobile":_teltext.text,@"pw":pwdtext,@"captchaType":_cptext.text};
 
    
    AFHTTPRequestOperation*op= [_manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSError*error;
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
        //NSLog(@"%@",dic);
       NSString *result = dic[@"code"];
        if (error==nil) {
            if ([result isEqualToString:@"4000"]){
                [[[UIAlertView alloc] initWithTitle: @"注册成功" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
                [self.view endEditing:YES];
                if (![dic[@"obj"] isEqual:[NSNull null]]) {
                    NSData *jsonData = [dic[@"obj"] dataUsingEncoding:NSUTF8StringEncoding];
                    NSError *err;
                    NSDictionary *data = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
                    [[NSUserDefaults standardUserDefaults] setObject:_teltext.text forKey:MemberUserName];
                    [[NSUserDefaults standardUserDefaults] setObject: data[@"Member_id"] forKey:MemberID];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    
          //          [self performSelector:@selector(connection) withObject:nil afterDelay:0.6];
                    [_nextButton setEnabled:YES];
                    _nextButton.backgroundColor = PinkColor;
                    
                }
                
                
                
            }else{
                [[[UIAlertView alloc] initWithTitle: @"注册失败" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
                [_nextButton setEnabled:YES];
                _nextButton.backgroundColor = PinkColor;
                return;
                
            }
            
            
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [[[UIAlertView alloc] initWithTitle: @"提交失败" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
        [_nextButton setEnabled:YES];
        _nextButton.backgroundColor = PinkColor;
    }];
    op.responseSerializer = [AFCompoundResponseSerializer serializer];
    [op start];
}
- (void)viewWillAppear:(BOOL)animated {
    _teltext.userInteractionEnabled = YES;
    [super viewWillAppear:animated];
}

@end
